<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
const departments = [
      { name: '张三', id: 1, pid: 0 },
      { name: '张四', id: 2, pid: 0 },
      { name: '张五', id: 3, pid: 0 },
      { name: '张小三', id: 4, pid: 1 },
      { name: '张小四', id: 5, pid: 2 },
      { name: '张小五', id: 6, pid: 3 }
    ]
  function listToTree(list,pid){
    const arr = []
    list.forEach(item =>{
     if (item.pid === pid){
      const children = listToTree(list,item.id)
      item.children = children
      arr.push(item)
      }
    })
    return arr
  }
  console.log(listToTree(departments,0));
  </script>
</body>
</html>
